<template>
  <div class="app-container table-app-container">
    <div class="fixed-table">
      <PageableTable
        :columns="insideColumns"
        :loading="loading"
        :data="insideTableData"
        :total="totalElements"
        :page="currentPage"
        :page-size="pageSize"
        :table-height="tableHeight"
        class="fixed-table-table"
        :show-advanced-search="!forSelection"
        @page-change="onPageChange"
        @sort-change="onSortChange"
        @selection-change="onSelectionChange"
        @open-drawer="onOpenDrawer"
        @close-filter-item="onCloseFilterItem"
      >
        <template v-for="column in insideColumns">
          <el-table-column v-if="column.display" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable" :fixed="column.fixed">
            <template slot-scope="scope">
              <column-render :render="column.render" :row="scope.row" :column="column" />
            </template>
          </el-table-column>
        </template>
      </PageableTable>
    </div>
  </div>
</template>

<script>
import PageableTable from '@neu/biz-core/components/PageableTable'
import { lifeCyclePage } from '@neu/dcam-ui/api/fixedAsset'
import { findByDictionaryType } from '@neu/dcam-ui/api/dictionary'
import databind from '@neu/biz-core/mixins/databind'
import { formatDate, isArray } from '@neu/biz-core/utils/utils'
import { listEffective } from '@neu/dcam-ui/api/assetExtFieldConfig'

const STATUS_MAP = {
  ruku: '入库',
  lingyong: '领用',
  pandian: '盘点',
  weixiu: '维修',
  scrap: '报废'
}

export default {
  name: 'PermissionsPage',
  components: {
    PageableTable
  },
  // 加入混入
  mixins: [databind],
  props: {
    asset: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      r: lifeCyclePage(this.asset),
      assetSource: [],
      assetStatus: [],
      valueType: [],
      useDepts: [],
      manageDepts: [],
      insideColumns: [
        { title: '操作时间', width: 150, key: 'createTime', render: (h, params) => { return h('span', formatDate(params.row.createTime, 'YYYY-MM-DD')) }, display: true },
        { title: '操作', width: 100, key: 'statusDesc', sortable: 'custom', display: true, render: (h, params) => {
          // const status = this.assetStatus.filter(t => {
          //   return t.code === params.row.statusDesc
          // })
          // const statusDesc = status.length === 1 ? status[0].text : params.row.statusDesc
          // if (statusDesc) {
          //   return h('span', [
          //     h('el-tag', statusDesc)
          //   ])
          // } else {
          //   return '-'
          // }
          return h('span', [
            h('el-tag', STATUS_MAP[params.row.statusDesc])
          ])
        } },
        { title: '资产编号', width: 150, key: 'code', sortable: 'custom', display: true },
        { title: '资产大类', width: 100, key: 'category', display: true },
        { title: '资产分类', width: 150, key: 'TypeName', display: true, sortable: 'custom', render: (h, params) => {
          return h('span', params.row.assetTypeName)
        } },
        { title: '资产名称', width: 300, key: 'name', sortable: 'custom', display: true },
        { title: '账套', width: 200, key: 'books', sortable: 'custom', display: true },
        { title: '投产时间', width: 150, key: 'userdate', render: (h, params) => { return h('span', formatDate(params.row.usedate, 'YYYY-MM-DD')) }, display: true },
        { title: '取得日期', width: 150, key: 'getdate', render: (h, params) => { return h('span', formatDate(params.row.getdate, 'YYYY-MM-DD')) }, display: true },
        { title: '自用价值', width: 100, key: 'ownvalue', display: true,
          render: (h, params) => {
            const val = params.row.ownvalue
            if (val && typeof (val) === 'number') {
              const result = val.toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
                return $1 + ','
              }).replace(/\.$/, '')
              return result
            } else {
              return '-'
            }
          } },
        { title: '折旧状态', width: 100, key: 'depreciationstatus', display: true },
        { title: '已提折旧月数', width: 100, key: 'depreciationmonth', display: true },
        { title: '累计折旧', width: 100, key: 'depreciationtotal', display: true,
          render: (h, params) => {
            const val = params.row.depreciationtotal
            if (val && typeof (val) === 'number') {
              const result = val.toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
                return $1 + ','
              }).replace(/\.$/, '')
              return result
            } else {
              return '-'
            }
          } },
        { title: '使用年限（月）', width: 120, key: 'month', display: true },
        { title: '价值类型', width: 100, key: 'valuetype', display: true, render: (h, params) => {
          const valutTyped = this.valueType.filter(t => {
            return t.code === params.row.valuetype
          })
          const valutTypeDesc = valutTyped.length === 1 ? valutTyped[0].text : params.row.valuetype
          if (valutTypeDesc) {
            return h('span', [
              h('el-tag', valutTypeDesc)
            ])
          } else {
            return '-'
          }
        } },
        { title: '价值', width: 120, key: 'money', display: true,
          render: (h, params) => {
            const val = params.row.money
            if (val && typeof (val) === 'number') {
              const result = val.toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
                return $1 + ','
              }).replace(/\.$/, '')
              return result
            } else {
              return '-'
            }
          } },
        { title: '财政性资金', width: 120, key: 'fundsfinancial', display: true,
          render: (h, params) => {
            const val = params.row.fundsfinancial
            if (val && typeof (val) === 'number') {
              const result = val.toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
                return $1 + ','
              }).replace(/\.$/, '')
              return result
            } else {
              return '-'
            }
          } },
        { title: '非财政性资金', width: 120, key: 'unfundsfinancial', display: true,
          render: (h, params) => {
            const val = params.row.unfundsfinancial
            if (val && typeof (val) === 'number') {
              const result = val.toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
                return $1 + ','
              }).replace(/\.$/, '')
              return result
            } else {
              return '-'
            }
          } },
        { title: '净值', width: 120, key: 'equity', display: true,
          render: (h, params) => {
            const val = params.row.equity
            if (val && typeof (val) === 'number') {
              const result = val.toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
                return $1 + ','
              }).replace(/\.$/, '')
              return result
            } else {
              return '-'
            }
          } },
        { title: '来源', width: 80, key: 'sourceDesc', display: true, render: (h, params) => {
          const source = this.assetSource.filter(t => {
            return t.code === params.row.sourceDesc
          })
          const sourceDesc = source.length === 1 ? source[0].text : params.row.sourceDesc
          if (sourceDesc) {
            return h('span', [
              h('el-tag', sourceDesc)
            ])
          } else {
            return '-'
          }
        } },
        { title: '使用方向', width: 100, key: 'usetype', display: true },
        { title: '使用部门', width: 100, key: 'useDeptDesc', sortable: 'custom', display: true, render: (h, params) => {
          const useDept = this.useDepts.filter(t => {
            return t.code === params.row.useDeptDesc
          })
          const useDesc = useDept.length === 1 ? useDept[0].text : params.row.useDeptDesc
          if (useDesc) {
            return h('span', [
              h('el-tag', useDesc)
            ])
          } else {
            return '-'
          }
        } },
        { title: '管理部门', width: 100, key: 'manageDeptDesc', sortable: 'custom', display: true, render: (h, params) => {
          const manage = this.manageDepts.filter(t => {
            return t.code === params.row.manageDeptDesc
          })
          const manageDesc = manage.length === 1 ? manage[0].text : params.row.manageDeptDesc
          if (manageDesc) {
            return h('span', [
              h('el-tag', manageDesc)
            ])
          } else {
            return '-'
          }
        } },
        { title: '使用人', width: 100, key: 'userName', display: true },
        { title: '数量', width: 60, key: 'quantity', display: true },
        { title: '制单人', width: 140, key: 'creator', display: true },
        { title: '所属单位', width: 140, key: 'belongTo', display: true },
        { title: '移交厅局', width: 240, key: 'submmitTo', display: true },
        { title: '原资产卡片单位', width: 240, key: 'secondDept', display: true, render: (h, params) => {
          const seconds = this.secondDepts.filter(t => {
            return t.code === params.row.secondDept
          })
          const second = seconds.length === 1 ? seconds[0].text : params.row.secondDept
          if (second) {
            return h('span', [
              h('el-tag', second)
            ])
          } else {
            return '-'
          }
        } },
        { title: '规格型号', width: 140, key: 'specification', display: true },
        { title: '存放地点', width: 140, key: 'located', display: true },
        { title: '原资产编号', width: 140, key: 'originCode', display: true },
        { title: '品牌', width: 100, key: 'brand', display: true },
        { title: '闲置价值', width: 80, key: 'idleValue', display: true,
          render: (h, params) => {
            const val = params.row.idleValue
            if (val && typeof (val) === 'number') {
              const result = val.toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
                return $1 + ','
              }).replace(/\.$/, '')
              return result
            } else {
              return '-'
            }
          } },
        { title: '制单时间', width: 180, key: 'handoverDate', render: (h, params) => { return h('span', formatDate(params.row.handoverDate, 'YYYY-MM-DD')) }, display: true },
        { title: '备用字段', width: 240, key: 'backup', display: true },
        { title: '备注', width: 240, key: 'remark', display: true },
        { title: '设备用途', width: 120, key: 'purpose', display: true },
        { title: '生成厂家', width: 120, key: 'produce', display: true },
        { title: '维保截止日期', width: 150, key: 'manufacturerEndDate', render: (h, params) => { return h('span', formatDate(params.row.manufacturerEndDate, 'YYYY-MM-DD')) }, display: true },
        { title: '对应接管文档是否齐整', width: 240, key: 'isDocumentAll', display: true },
        { title: '对应支撑的业务应用系统', width: 200, key: 'businessSystem', display: true },
        { title: '合同名称以及编号', width: 150, key: 'contractNameAndCode', display: true },
        { title: '序列号', width: 150, key: 'sequence', display: true },
        { title: '是否报废', width: 80, key: 'isScrapped', display: true },
        { title: '厅局机房地址', width: 240, key: 'officeComputerRoomAddress', display: true },
        { title: '厅局地址', width: 240, key: 'officeAddress', display: true },
        { title: '是否在线', width: 80, key: 'running', display: true }
      ],
      dialogFormVisible: false,
      dialogViewVisible: false,
      dialogStatus: 'create',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      editId: -1,
      secondDepts: [],
      thirdDepts: [],
      drawerFormVisible: false,
      /** 有效扩展属性 */
      effictiveExtField: []
    }
  },
  mounted() {
    const extColumns = []
    listEffective().then(response => {
      this.effictiveExtField = response.data
      this.effictiveExtField.forEach((item, index) => {
        if (item.extColumn === 'ext1') {
          extColumns.push({ title: item.name, width: 90, key: 'ext1TsName', render: (
            h, params) => {
            if (item.dataType === 'dateselect') {
              return h('span', formatDate(params.row.ext1TsName))
            } else {
              return h('span', params.row.ext1TsName)
            }
          }, display: item.showed })
        }
        if (item.extColumn === 'ext2') {
          extColumns.push({ title: item.name, width: 90, key: 'ext2TsName', render: (
            h, params) => {
            if (item.dataType === 'dateselect') {
              return h('span', formatDate(params.row.ext2TsName))
            } else {
              return h('span', params.row.ext2TsName)
            }
          }, display: item.showed })
        }
        if (item.extColumn === 'ext3') {
          extColumns.push({ title: item.name, width: 90, key: 'ext3TsName', render: (
            h, params) => {
            if (item.dataType === 'dateselect') {
              return h('span', formatDate(params.row.ext3TsName))
            } else {
              return h('span', params.row.ext3TsName)
            }
          }, display: item.showed })
        }
        if (item.extColumn === 'ext4') {
          extColumns.push({ title: item.name, width: 90, key: 'ext4TsName', render: (
            h, params) => {
            if (item.dataType === 'dateselect') {
              return h('span', formatDate(params.row.ext4TsName))
            } else {
              return h('span', params.row.ext4TsName)
            }
          }, display: item.showed })
        }
        if (item.extColumn === 'ext5') {
          extColumns.push({ title: item.name, width: 90, key: 'ext5TsName', render: (
            h, params) => {
            if (item.dataType === 'dateselect') {
              return h('span', formatDate(params.row.ext5TsName))
            } else {
              return h('span', params.row.ext5TsName)
            }
          }, display: item.showed })
        }
      })
      this.insideColumns = this.insideColumns.concat(extColumns)
    })

    findByDictionaryType('assetSource').then(res => {
      if (res.status === 'success') {
        this.assetSource = res.data
      }
    })
    findByDictionaryType('valueType').then(res => {
      if (res.status === 'success') {
        this.valueType = res.data
      }
    })
    findByDictionaryType('useDept').then(res => {
      this.useDepts = res.data
    })
    findByDictionaryType('secondDept').then(response => {
      this.secondDepts = response.data
    })
    findByDictionaryType('thirdDept').then(response => {
      this.thirdDepts = response.data
    })
    findByDictionaryType('assetStatus').then(response => {
      this.assetStatus = response.data
    })
    findByDictionaryType('manageDept').then(res => {
      if (res.status === 'success') {
        this.manageDepts = res.data
      }
    })
    findByDictionaryType('assetStatus').then(res => {
      if (res.status === 'success') {
        this.assetStatus = res.data
      }
    })
  },
  methods: {
    stateFormat(row, column, cellValue) {
      cellValue += ''
      if (!cellValue.includes('.')) cellValue += '.'
      return cellValue.replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
        return $1 + ','
      }).replace(/\.$/, '')
    },
    onSearch() { // 筛选-筛选
      this.$refs.filterForm.search()
      this.drawerFormVisible = false
    },
    onReset() { // 筛选-重置
      this.$refs.filterForm.reset()
      this.drawerFormVisible = false
    },
    onOpenDrawer() { // 筛选-打开抽屉
      this.drawerFormVisible = true
      this.$refs.actionBar.clearForm()
    },
    onCloseFilterItem(item) {
      this.$refs.filterForm.onFilterItemClose(item)
    },
    view(id) {
      // 打开对话框
      this.editId = id
      this.dialogViewVisible = true
    },
    edit(selections) {
      if (isArray(selections)) {
        if (selections.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择操作数据！'
          })
          return
        }
        if (selections.length > 1) {
          this.$message({
            type: 'warning',
            message: '只能选择一条数据！'
          })
          return
        }
        // 更新当前被编辑实体的ID，自动传递至编辑表单
        this.editId = selections[0].id
        // 打开对话框
        this.dialogFormVisible = true
      }
    },
    ok() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        // 调用asset-table实例的mixin方法refresh()，更新表格
        this.refresh()
        // 关闭对话框
        this.dialogFormVisible = false
      })
    },
    cancel() {
      this.editId = -1
      this.$refs.editForm.reset()
      this.dialogFormVisible = false
    },
    viewCancel() {
      this.editId = -1
      // 关闭对话框
      this.dialogViewVisible = false
    }
  }
}
</script>
